<script setup>
import {addUser, del, getUsers, update} from '@/lib/user'
import {ref} from 'vue'
import {ElMessage} from "element-plus";
import axios, {get} from './lib/http'
import {Calendar} from '@element-plus/icons-vue'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'

const msg = ref({id: 0, name: ''})

function abc() {
  getUsers('/users', {}, d => {
    ElMessage(d.name)
    console.log(d)
  })
}

function abc2() {
  get('/users').then(d => {
    ElMessage(d.name)
    console.log(d)
  })
}

function aa() {
  axios.get("/users").then(res => {
    ElMessage(res.name)
  })
}

function dd(a, b, c) {
  c(a, b)
}

function bb() {
  dd(20, 30, (a, b) => {
    console.log(a, b, 'a+b=', a + b)
  })
}

const form = ref({
  name: '李四',
  account: 'admin',
  password: '123',
  birthday: '2013-10-25'
})

function gets() {
  get('/users').then(res => {
    console.log(res)
  })
}

function add() {
  addUser("/addUser", form.value, data => {
    if (data.code === 200) {
      ElMessage({type: 'success', message: data.msg})
    } else {
      ElMessage({type: 'error', message: data.msg})
    }
    currpage.value = 1
    getTableData()
  })
}


const tableData = ref()

const pagesize = ref(3)
const total = ref(50)
const currpage = ref(1)
const loading = ref(false)

function getTableData() {
  loading.value = true
  //       url        get传参                                                         回调函数

  getUsers('/pages', {params: {currpage: currpage.value, pagesize: pagesize.value}}, data => {
    tableData.value = data.data
    total.value = parseInt(data.total)
    loading.value = false
  })

}

getTableData()


//分页处理
const handleCurrentChange = curr => {
  currpage.value = curr
  console.log(`current page: ${curr}`)
  getTableData()
}

const deluser = (a, b) => {
  del('/remove', {params: {id: a}}, data => {
    if (data.code === 200) {
      ElMessage({type: 'success', message: data.msg})
      getTableData()
    } else if (data.code === 400) {
      ElMessage({message: data.msg, type: 'error'})
    }
  })
}


const enable = ref(true)


function handleSelectionChange(values) {
  multipleSection.value = values
  if (multipleSection.value.length > 0) {
    enable.value = false
  } else {
    enable.value = true
  }
  console.log("选择", values)
}


const multipleTableRef = ref()
const multipleSection = ref()

function allyes() {
  multipleTableRef.value.toggleAllSelection()
  //tableData.value.forEach(row=>{
  //console.log(multipleTableRef.value)
  //multipleTableRef.value.toggleRowSelection(row)


  //console.log(row)
  //})
}

function noall() {
  // multipleTableRef.value.toggleRowSelection()
  tableData.value.forEach(row => {
    multipleTableRef.value.toggleRowSelection(row)
  })
}

function allno() {
  multipleTableRef.value.clearSelection()
}

function delselect() {
  multipleSection.value.forEach(row => {
    deluser(row.id)
  })
}


function delsel() {
  let id = ''
  let aa = []
  multipleSection.value.forEach(row => {
    aa.push(`ids=${row.id}`)
  })
  id = aa.join('&')
  axios.delete(`/delall?${id}`).then(data => {
    if (data.code === 200) {
      ElMessage({type: 'success', message: data.msg})
      getTableData()
    } else if (data.code === 400) {
      ElMessage({message: data.msg, type: 'error'})
    }
  })
  getTableData()

}

function delselbak() {
  axios.get('/delall', {
    params: {
      ids: [11, 22, 33, 44, 55]
    },

    paramsSerializer: function (params) {
      const keys = Object.keys(params)
      const arr = []
      keys.forEach(item => {
        if (Array.isArray(params[item])) {
          const url = params[item].map(_ => `${item}=${_}`).join('&')
          arr.push(url)
        } else {
          arr.push(`${item}=${params[item]}`)
        }
      })
      const result = arr.join('&')
      console.log(result)
      return `${result}`
    }
  })
}


//使用el-dialog 实现新增数据 和 编辑数据
const dialogFormVisible = ref(false)

function adduser(f,user) {
  dialogFormVisible.value = true
  if (f) {
    info.value.title = '新增用户'
    info.value.submittext = '新增'
    info.value.flag = true
  } else {
    info.value.title = '编辑用户资料'
    info.value.submittext = '更新'
    info.value.flag = false
    form.value = user
  }
}

const info = ref({
  title: '新增用户',
  flag: true,
  submittext: '新增'
})

//ajax 调用编辑接口
function edit(){
  update('/update',form.value,res=>{

    getTableData()
  })
}

function addusersave() {
  dialogFormVisible.value = false
  if (info.value.flag) {
    console.log("add()新增用户")
    add()
  } else {
    console.log("edit()编辑用户")
    edit()
    delete form.value.id
  }
  getTableData()
}

</script>

<template>
  <el-dialog v-model="dialogFormVisible" style="width:550px" :title="info.title">
    <el-row>
      <el-col :span="20" :offset="2">
        <el-form :model="form" label-width="120px">
          <el-form-item label="姓名">
            <el-input v-model="form.name"/>
          </el-form-item>

          <el-form-item label="账号">
            <el-input type="text" v-model="form.account"/>
          </el-form-item>

          <el-form-item label="密码">
            <el-input type="password" v-model="form.password" show-password/>
          </el-form-item>
          <el-form-item label="出生日期">
            <el-col :span="11">
              <el-config-provider :locale="zhCn">
                <el-date-picker
                    v-model="form.birthday"
                    type="date"
                    placeholder="请选择出生日期"
                    style="width: 100%"/>
              </el-config-provider>
            </el-col>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="addusersave(true)">{{ info.submittext }}</el-button>
      </span>
    </template>
  </el-dialog>

  <h3>{{ msg.name }}</h3>
  <el-button @click="abc">get-abc</el-button>
  <el-button @click="abc2">get-abc2</el-button>
  <el-button @click="aa">get-aa</el-button>
  <el-button @click="bb">get-bb</el-button>
  <el-button @click="gets">get-get</el-button>

  <!-- 添加用户 -->
  <el-row>
    <el-col :span="20" :offset="2">
      <el-form :model="form" label-width="120px">
        <el-form-item label="姓名">
          <el-input v-model="form.name"/>
        </el-form-item>

        <el-form-item label="账号">
          <el-input type="text" v-model="form.account"/>
        </el-form-item>

        <el-form-item label="密码">
          <el-input type="password" v-model="form.password"/>
        </el-form-item>
        <el-form-item label="出生日期">
          <el-col :span="11">
            <el-config-provider :locale="zhCn">
              <el-date-picker
                  v-model="form.birthday"
                  type="date"
                  placeholder="请选择出生日期"
                  style="width: 100%"/>
            </el-config-provider>
          </el-col>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="add">添加新用户</el-button>
          <el-button>取消</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>


  <!-- 全选 反选 取消 删除选择 -->
  <el-row>
    <el-col :span="20" :offset="2">
      <el-button type="success" size="small" @click="allyes">全选</el-button>
      <el-button type="success" size="small" @click="noall">反选</el-button>
      <el-button type="success" size="small" @click="allno">取消</el-button>

      <!-- 没有选择不能使用删除 -->
      <el-button type="warning" size="small" :disabled="enable" @click="delselect">删除选择</el-button>
      <el-button type="danger" size="small" :disabled="enable" @click="delsel">批量删除选择</el-button>

      <!-- 新增对话框 -->
      <el-button type="success" size="small" @click="adduser(true)">新增用户</el-button>
    </el-col>
  </el-row>
  <div style="margin:15px"></div>

  <!-- 显示数据并分页显示 -->
  <el-row>
    <el-col :span="20" :offset="2">
      <el-table :data="tableData" border stripe v-loading="loading"
                element-loading-text="加载..."
                @selection-change="handleSelectionChange"
                ref="multipleTableRef"
      >
        <!-- 行号功能 -->
        <!--<el-table-column label="行号" type="index"/>-->

        <!-- 多选删除功能 -->
        <el-table-column type="selection" width="55"/>


        <el-table-column prop="name" label="姓名"/>
        <el-table-column prop="account" label="账号"/>
        <el-table-column prop="password" label="密码"/>
        <!--<el-table-column prop="birthday" label="出生日期"/>-->
        <el-table-column label="Date" width="180">
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <el-icon>
                <Calendar/>
              </el-icon>
              <span style="margin-left: 10px">{{ scope.row.birthday }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="常用操作" min-width="100%">
          <template #default="scope">
            <el-button type="primary" size="small">审核</el-button>
            <el-button type="success" size="small">查看</el-button>
            <el-button type="warning" size="small" @click="adduser(false,scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="deluser(scope.row.id,scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-col>
  </el-row>
  <!-- 分页实现 -->
  <el-row style="margin-top: 10px;">
    <el-col :span="20" :offset="2">
      <el-pagination style="justify-content: center"
                     background
                     layout="prev, pager, next"
                     :total="total"
                     :page-size="pagesize"
                     :current-page="currpage"
                     @current-change="handleCurrentChange"
      />
    </el-col>
  </el-row>


  <div style="margin:50px"></div>
  <el-row>
    <el-col style="display:flex;justify-content: center;">
      <el-form
          label-position="right"
          label-width="100px"
          style="max-width: 460px;"
      >
        <el-form-item label="姓名">
          <el-input/>
        </el-form-item>
        <el-form-item label="账号">
          <el-input/>
        </el-form-item>
        <el-form-item label="联系地址">
          <el-input/>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>


</template>
<style scoped>
</style>
